package RSAGUI;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

import RSA.Key;


public class MonSocket extends Thread{
	
	private ServerSocket m_serverSocket;
	private Socket m_socket;
	
	private int m_port;
	
	private Socket m_socket_client;
	private Interface m_parent;
	
	public MonSocket(int port, Interface parent)
	{
		m_parent = parent;
		m_port=port;
		
		//Client part -------------------------------------
		m_socket_client = new Socket();
		//Client part -------------------------------------
		
	}
		
	public void logPrint(String x)
	{
		if(m_parent!=null) m_parent.writeln(x);
	}
	
	public void send(Object x)
	{
		try {
			InetAddress server = InetAddress.getByName("localhost");
			//m_parent.writeln("(Connexion sur le port "+m_port+" )");
			m_socket_client.connect(new InetSocketAddress(server, m_port));
			ObjectOutputStream out = new ObjectOutputStream(m_socket_client.getOutputStream());
			
			out.writeObject(x);
			out.flush();
			
			m_socket_client.close();
			//m_parent.writeln("(Fermeture de le connexion sur le port "+m_port+" )");
		} catch (IOException e) {
			m_parent.writeln("Il semble que le serveur ne soit pas connecté, vérifiez et recommencez\n("+e.getMessage()+")");
			//e.printStackTrace();
		}
	}
	
	public static void affiche(Object x) {
		try
		{
			byte[] tab = (byte [])x;
			for(int i=0;i<tab.length;i++) System.out.print(tab[i]+" ");
			System.out.println();
		}
		catch(Exception e){}
	}

	public void run()
	{
		//Server part -------------------------------------
			try
			{
				m_serverSocket = new ServerSocket(m_port);

				m_socket = m_serverSocket.accept();
				if (m_socket!=null) 
				{
					//logPrint("Connection détectée");
					ObjectInputStream in = new ObjectInputStream(m_socket.getInputStream());
					Object result =  in.readObject();
					try
					{
						Key p = (Key)result;
						if(m_parent!=null) m_parent.setPublicKey(p);
					}
					catch(ClassCastException e)
					{
						byte[] b = (byte[])result;
						if(m_parent!=null) m_parent.writeMessageFromBytes(b);
					}
					m_socket.close();
					m_serverSocket.close();
					//logPrint(in.readLine());
				}

			}catch(Exception e)
			{
				//logPrint(e.getMessage());
				//e.printStackTrace();
			}
			//Server part -------------------------------------
		}
	


		public void closeAllSockets() {
			try {
				if(m_serverSocket != null) m_serverSocket.close();
				if(m_socket != null) m_socket.close();
			} catch (IOException e) {
				logPrint(e.getMessage());
			}
			m_parent.writeln("Serveur éteint ("+m_parent.getName()+" n'attend plus de clé publique)");
		}

}
